package com.suiwei.frame;

import org.junit.jupiter.api.Test;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.TimeUnit;

/**
 * @author suiwei
 * @date 2022-10-25 11:40
 */
@SpringBootTest
public class Quartz {
    @Test
    void  test() throws Exception {
        //调用步骤
        //1.创建一个任务调度工厂
        SchedulerFactory factory = new StdSchedulerFactory();
        //2.根据工厂得到一个任务调度器
        Scheduler scheduler = factory.getScheduler();
        //3.创建JobDetail实例（任务封装类），并绑定要执行的任务。withIdentity传入一个名字，一个组。usingJobData传递参数
        JobDetail jobDetail = JobBuilder.newJob(com.suiwei.quartz.job.Test.class).usingJobData("message","suiwei")
                .withIdentity("job1", "group1").build();
        //4.1简单触发器SimpleTrigger（实际开发几乎不用）,startNow立即触发,withSchedule触发规则
//        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group2").startNow().withSchedule(
//                //每3秒执行一次，一直执行
//                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever()
//        ).build();
        //4.2CronTrigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group2").startNow().withSchedule(
                CronScheduleBuilder.cronSchedule("0/2 * * * * ?")
        ).build();
        //5.调度
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
        //让主线程暂时不关闭，方便查看效果
        TimeUnit.MINUTES.sleep(1);
        //6.关闭，线程相关的都要关闭
        scheduler.shutdown();

    }


}
